#pragma once
#include <iostream>
#include <string>

#include "Init.hpp"

extern Log log;
Init init;

class Task
{
public:
    Task(int sockfd, const std::string& clientip, const uint16_t& clientport)
        :_sockfd(sockfd), _clientip(clientip), _clientport(clientport)
    {}

    void run()
    {
        char buffer[4096];
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));   // tcp是面向字节流的，可以像读写文件一样读写网络
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "[client]$ " << buffer << endl;
            // string message = "tcpserver echo# ";
            // message += buffer;

            string message = init.Translation(buffer);

            // sleep(5);
            // log(Warning, "sockfd close %d done", _sockfd);
            // sleep(2);

            int n = write(_sockfd, message.c_str(), message.size());    // 数据处理后写回客户端
            if(n < 0)
            {
                log(Error, "write error, errno: %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if(n == 0)
        {
            log(Info, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);    
        }
        else 
        {
            log(Error, "read error, sockfd: %d, clientip: %s, clientport: %d", _sockfd, _clientip.c_str(), _clientport);
        }
        close(_sockfd);
    }

    void operator()()
    {
        run();
    }
    
    ~Task(){}
private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
}; 